 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Lib
 * Package  : net.solosky.easyavatar.api.impl
 * File     : AbstractOAuthFriendProvider.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2011-10-25
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.api.impl;

import java.io.IOException;

import net.solosky.easyavatar.api.OAuthFriendProvider;

import org.scribe.exceptions.OAuthException;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

/**
 * 
 * 抽象的OAuth好友提供者，保存了OAuthService和Token
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public abstract class AbstractOAuthFriendProvider implements OAuthFriendProvider {
	/**OAuth服务接口*/
	private OAuthService oAuthService;
	/**已经授权的访问令牌*/
	private Token accessToken;
	@Override
	public OAuthService createOAuthService(String appKey, String appSecret, String callback) {
		if(oAuthService==null)
			oAuthService = doCreateOAuthService(appKey, appSecret, callback);
		return oAuthService;
	}
	
	@Override
	public void setAccessToken(Token accessToken) {
		this.accessToken = accessToken;
	}
	
	/***
	 * 创建一个OAuth请求
	 * @param verb
	 * @param url
	 * @return
	 */
	protected OAuthRequest createOAuthRequest(Verb verb, String url){
		return new OAuthRequest(verb, url);
	}
	
	/**
	 * 执行一个OAuth请求
	 * @param request
	 * @return
	 * @throws OAuthException
	 */
	protected Response executeAuthRequest(OAuthRequest request) throws IOException{
		try{
			oAuthService.signRequest(accessToken, request);
			return request.send();
		}catch(OAuthException e){
			throw new IOException(e.getMessage());
		}
	}
	
	/**
	 * 创建OAuth服务，子类需实现
	 * @return
	 */
	protected abstract OAuthService doCreateOAuthService(
			String appKey, String appSecret, String callback);
	
	
}
